import api from "../../utils/api";
import Utils from "../../utils/utils";

// pages/malldetail/malldetail.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: undefined as number | undefined,//当前ID
    eventInfo: {} as EventModel,
    code: "" as string,//活动码
    type: "" as string,//跳转类型,activity-活动商品,normal-正常商品
    commodityDetail: {} as CommodityModel,//商品详情
    currentIndex: 1 as number,//当前展示的图片索引
    discount: '' as string,//折扣
    num:0 as number,//购物车内容数量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    console.log(options)
    if (options.type == "activity") {
      const info = JSON.parse(options.info)
      this.setData({
        eventInfo: info,
        code: options.code
      })
    }
    if (options.id) {
      const id = Number(options.id)
      this.getCommodityDetail(id)
    }
    const app = getApp<IAppOption>();
    this.setData({
      statusHeight: app.globalData.statusBarHeight,
      navHeight: app.globalData.navHeight,
      type: options.type,
      id: Number(options.id)
    })
  },
  toBack() {
    wx.navigateBack();
  },
  // 获取详情
  getCommodityDetail(id: number): void {
    const params = {
      id,
      eventCode: this.data.code
    }
    api.commodity.getCommodityDetail(params).then(res => {
      if (res.data.code == "000") {
        let discount
        if (res.data.data) {
          if (typeof res.data.data.price !== 'number' || typeof res.data.data.originalPrice !== 'number') {
            throw new Error('price and originalPrice must be numbers');
          }
          discount = res.data.data.price / res.data.data.originalPrice;
          discount = (discount * 10 ).toFixed(1);
          res.data.data.price = Utils.priceToYuan(res.data.data.price as number)
          res.data.data.originalPrice = Utils.priceToYuan(res.data.data.originalPrice as number)
        }
        this.setData({
          commodityDetail: res.data.data,
          discount
        })
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 切换swiper
  changeSwiper(e: any): void {
    this.setData({
      currentIndex: e.detail.current + 1
    })
  },
  // 立即购买
  imBuy(): void {
    try {
      const { code, type, id, eventInfo } = this.data
      const commodity: OrderCommodity = {
        commodityId: id as number,
        count: 1,
      }
      const params = {
        autoSelectCoupon: true,
        orderCommodities: [
          commodity
        ],
        eventCode: code,
        fromCart: false
      } as PreviewOrderParam
      api.order.previewOrder(params).then(res => {
        if (res.data.code == "000") {
          const previewInfo = JSON.stringify(res.data.data)
          wx.navigateTo({
            url: "/pages/order/order?data=" + encodeURIComponent(previewInfo) + '&fromCart=0&eventCode=' + code,
          })
        } else {
          wx.showToast({
            title: res.data.message as string,
            icon: "error"
          })
        }
      })
    } catch (error) {
      console.error("error")
    }
  },
  // 加入购物车
  addCart(): void {
    const {id} = this.data
    const params: CartAddToCartParam = {
      commodityId: id,
      count:1
    }
    api.cart.addToCart(params).then(res => {
      if(res.data.code == "000") {
        this.getCartContentCount()
      }else {
        wx.showToast({
          title: res.data.message as string,
          icon:"error"
        })
      }
    })
  },
  // 获取购物车数量
  getCartContentCount(): void {
    api.cart.getCartContentCount().then(res => {
      if(res.data.code == "000") {
        this.setData({
          num: res.data.data
        })
      }
      else {
        wx.showToast({
          title: res.data.message as string,
          icon:"error"
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(this.data.type == "normal") {
      this.getCartContentCount();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})